package com.example.screenrecorder;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.projection.MediaProjectionManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

import java.util.List;

/**
 * 主界面Activity - 屏幕录制应用的主入口
 * 负责权限管理、界面控制、录制启动等核心功能
 * 提供用户友好的操作界面和状态显示
 */
public class MainActivity extends AppCompatActivity {
    
    // ========== 常量定义 ==========
    private static final int REQUEST_CODE_SCREEN_CAPTURE = 1001;    // 屏幕录制权限请求码
    private static final int REQUEST_CODE_OVERLAY_PERMISSION = 1002; // 悬浮窗权限请求码
    private static final int REQUEST_CODE_STORAGE_PERMISSION = 1003; // 存储权限请求码
    
    // ========== 界面控件 ==========
    private Button btnStartRecording;      // 开始录制按钮
    private Button btnStopRecording;       // 停止录制按钮
    private Button btnSettings;            // 基本设置按钮
    private Button btnAdvancedSettings;    // 高级设置按钮
    private Button btnHistory;             // 录制历史按钮
    private Button btnTest;                // 功能检查按钮
    
    // ========== 状态变量 ==========
    private boolean isRecording = false;  // 录制状态标志
    private MediaProjectionManager mediaProjectionManager; // 媒体投影管理器
    
    /**
     * Activity创建时的初始化方法
     * 设置界面、初始化控件、检查权限等
     * @param savedInstanceState 保存的实例状态
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // 设置主界面布局
        
        initViews();           // 初始化界面控件
        setupClickListeners(); // 设置点击监听器
        checkPermissions();    // 检查应用权限
        
        // 获取媒体投影管理器，用于屏幕录制
        mediaProjectionManager = (MediaProjectionManager) getSystemService(MEDIA_PROJECTION_SERVICE);
    }
    
    /**
     * 初始化界面控件
     * 获取所有按钮控件的引用并设置初始状态
     */
    private void initViews() {
        btnStartRecording = findViewById(R.id.btn_start_recording);      // 获取开始录制按钮
        btnStopRecording = findViewById(R.id.btn_stop_recording);         // 获取停止录制按钮
        btnSettings = findViewById(R.id.btn_settings);                   // 获取基本设置按钮
        btnAdvancedSettings = findViewById(R.id.btn_advanced_settings); // 获取高级设置按钮
        btnHistory = findViewById(R.id.btn_history);                     // 获取录制历史按钮
        btnTest = findViewById(R.id.btn_test);                          // 获取功能检查按钮
        
        updateButtonStates(); // 更新按钮状态（初始时停止按钮禁用）
    }
    
    /**
     * 设置按钮点击监听器
     * 为所有按钮绑定对应的点击事件处理方法
     */
    private void setupClickListeners() {
        btnStartRecording.setOnClickListener(v -> startScreenRecording());     // 开始录制按钮点击事件
        btnStopRecording.setOnClickListener(v -> stopScreenRecording());       // 停止录制按钮点击事件
        btnSettings.setOnClickListener(v -> openSettings());                   // 基本设置按钮点击事件
        btnAdvancedSettings.setOnClickListener(v -> openAdvancedSettings());   // 高级设置按钮点击事件
        btnHistory.setOnClickListener(v -> openHistory());                     // 录制历史按钮点击事件
        btnTest.setOnClickListener(v -> openTestActivity());                    // 功能检查按钮点击事件
    }
    
    /**
     * 检查应用所需权限
     * 使用原生权限申请方式
     */
    private void checkPermissions() {
        // 申请基本权限
        requestBasicPermissions();
    }
    
    /**
     * 申请基本权限（不包含存储权限）
     */
    private void requestBasicPermissions() {
        String[] permissions = {
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.POST_NOTIFICATIONS,
            Manifest.permission.CAMERA
        };
        
        ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_SCREEN_CAPTURE);
    }
    
    private void checkOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!Settings.canDrawOverlays(this)) {
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                        Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent, REQUEST_CODE_OVERLAY_PERMISSION);
            }
        }
    }
    
    private void startScreenRecording() {
        if (!isRecording) {
            Log.d("MainActivity", "Starting screen recording request...");
            
            // 检查存储权限
            if (!checkStoragePermission()) {
                Log.d("MainActivity", "Storage permission not granted, requesting...");
                Toast.makeText(this, "需要存储权限才能保存录制文件", Toast.LENGTH_SHORT).show();
                
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    // Android 13+ 使用新的媒体权限
                    Log.d("MainActivity", "Requesting media permissions for Android 13+");
                    String[] mediaPermissions = {
                        Manifest.permission.READ_MEDIA_VIDEO,
                        Manifest.permission.READ_MEDIA_IMAGES,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                    };
                    Log.d("MainActivity", "Requesting media permissions: " + java.util.Arrays.toString(mediaPermissions));
                    ActivityCompat.requestPermissions(this, mediaPermissions, REQUEST_CODE_STORAGE_PERMISSION);
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    // Android 11-12 尝试多种权限申请方式
                    Log.d("MainActivity", "Requesting storage manager permission for Android 11-12");
                    
                    try {
                        // 首先尝试跳转到应用设置页面
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        intent.setData(Uri.parse("package:" + getPackageName()));
                        startActivityForResult(intent, REQUEST_CODE_STORAGE_PERMISSION);
                    } catch (Exception e) {
                        Log.e("MainActivity", "Failed to open app settings", e);
                        // 如果失败，尝试传统权限申请
                        String[] storagePermissions = {
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                        };
                        Log.d("MainActivity", "Fallback to traditional permissions: " + java.util.Arrays.toString(storagePermissions));
                        ActivityCompat.requestPermissions(this, storagePermissions, REQUEST_CODE_STORAGE_PERMISSION);
                    }
                } else {
                    // Android 10 及以下使用传统权限申请
                    String[] storagePermissions = {
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE
                    };
                    Log.d("MainActivity", "Requesting storage permissions: " + java.util.Arrays.toString(storagePermissions));
                    ActivityCompat.requestPermissions(this, storagePermissions, REQUEST_CODE_STORAGE_PERMISSION);
                }
                return;
            } else {
                Log.d("MainActivity", "Storage permission already granted, proceeding to screen capture");
            }
            
            Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
            startActivityForResult(captureIntent, REQUEST_CODE_SCREEN_CAPTURE);
        } else {
            Log.w("MainActivity", "Recording already in progress");
        }
    }
    
    /**
     * 检查存储权限
     */
    private boolean checkStoragePermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13+ 使用新的媒体权限模型
            boolean hasVideoPermission = ContextCompat.checkSelfPermission(this, 
                Manifest.permission.READ_MEDIA_VIDEO) == PackageManager.PERMISSION_GRANTED;
            boolean hasImagesPermission = ContextCompat.checkSelfPermission(this, 
                Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED;
            boolean hasWritePermission = ContextCompat.checkSelfPermission(this, 
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
            
            Log.d("MainActivity", "Android 13+ permissions - Video: " + hasVideoPermission + 
                  ", Images: " + hasImagesPermission + ", Write: " + hasWritePermission);
            
            // Android 13+ 只要有媒体权限就认为可以写入
            // 因为WRITE_EXTERNAL_STORAGE在Android 13+中可能不再有效
            return hasVideoPermission || hasImagesPermission || hasWritePermission;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            // Android 11-12 检查存储管理权限
            boolean hasManagerPermission = Environment.isExternalStorageManager();
            Log.d("MainActivity", "Android 11-12 storage manager permission: " + hasManagerPermission);
            
            // 如果没有管理权限，检查传统权限
            if (!hasManagerPermission) {
                boolean hasWritePermission = ContextCompat.checkSelfPermission(this, 
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
                Log.d("MainActivity", "Traditional write permission: " + hasWritePermission);
                return hasWritePermission;
            }
            return hasManagerPermission;
        } else {
            // Android 10 及以下使用传统存储权限
            boolean hasPermission = ContextCompat.checkSelfPermission(this, 
                Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
            Log.d("MainActivity", "Traditional storage permission: " + hasPermission);
            return hasPermission;
        }
    }
    
    /**
     * 请求存储权限
     */
    private void requestStoragePermission() {
        Log.d("MainActivity", "Requesting storage permission...");
        ActivityCompat.requestPermissions(this, 
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 
            REQUEST_CODE_STORAGE_PERMISSION);
    }
    
    private void stopScreenRecording() {
        if (isRecording) {
            Intent serviceIntent = new Intent(this, ScreenRecordService.class);
            serviceIntent.setAction(ScreenRecordService.ACTION_STOP_RECORDING);
            startService(serviceIntent);
            
            isRecording = false;
            updateButtonStates();
            Toast.makeText(this, "停止录制", Toast.LENGTH_SHORT).show();
        }
    }
    
    private void openSettings() {
        // 打开基本设置界面
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }
    
    private void openAdvancedSettings() {
        // 打开高级设置界面
        Intent intent = new Intent(this, AdvancedSettingsActivity.class);
        startActivity(intent);
    }
    
    private void openHistory() {
        // 打开录制历史界面
        Toast.makeText(this, "录制历史功能开发中...", Toast.LENGTH_SHORT).show();
    }
    
    private void openTestActivity() {
        // 打开功能检查界面
        Intent intent = new Intent(this, TestActivity.class);
        startActivity(intent);
    }
    
    private void updateButtonStates() {
        btnStartRecording.setEnabled(!isRecording);
        btnStopRecording.setEnabled(isRecording);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == REQUEST_CODE_SCREEN_CAPTURE) {
            if (resultCode == Activity.RESULT_OK) {
                startRecordingService(data);
            } else {
                Toast.makeText(this, "屏幕录制权限被拒绝", Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == REQUEST_CODE_OVERLAY_PERMISSION) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (!Settings.canDrawOverlays(this)) {
                    Toast.makeText(this, "需要悬浮窗权限才能显示录制控制", Toast.LENGTH_LONG).show();
                }
            }
        }
    }
    
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        
        if (requestCode == REQUEST_CODE_SCREEN_CAPTURE) {
            // 基本权限申请结果
            boolean allGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allGranted = false;
                    break;
                }
            }
            
            if (allGranted) {
                Log.d("MainActivity", "Basic permissions granted");
                checkOverlayPermission();
            } else {
                Toast.makeText(this, "需要基本权限才能使用屏幕录制功能", Toast.LENGTH_LONG).show();
            }
        } else if (requestCode == REQUEST_CODE_STORAGE_PERMISSION) {
            // 存储权限申请结果
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("MainActivity", "Storage permission granted, starting screen capture...");
                Intent captureIntent = mediaProjectionManager.createScreenCaptureIntent();
                startActivityForResult(captureIntent, REQUEST_CODE_SCREEN_CAPTURE);
            } else {
                Log.d("MainActivity", "Storage permission denied");
                Toast.makeText(this, "需要存储权限才能保存录制文件", Toast.LENGTH_LONG).show();
            }
        }
    }
    
    private void startRecordingService(Intent data) {
        Intent serviceIntent = new Intent(this, ScreenRecordService.class);
        serviceIntent.setAction(ScreenRecordService.ACTION_START_RECORDING);
        serviceIntent.putExtra(ScreenRecordService.EXTRA_RESULT_CODE, RESULT_OK);
        serviceIntent.putExtra(ScreenRecordService.EXTRA_RESULT_DATA, data);
        startService(serviceIntent);
        
        isRecording = true;
        updateButtonStates();
        Toast.makeText(this, "开始录制", Toast.LENGTH_SHORT).show();
    }
    
    @Override
    protected void onResume() {
        super.onResume();
        // 检查录制状态
        if (ScreenRecordService.isRecording()) {
            isRecording = true;
            updateButtonStates();
        }
    }
}
